package musicstore.com.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import musicstore.com.dao.UserDao;
import musicstore.com.dao.impl.UserDaoImpl;
import musicstore.com.entity.User;

public class RegisterServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		UserDao dao = new UserDaoImpl();
		
		if(dao.checkUser(username)){
			request.setAttribute("error", "用户已重复");
			RequestDispatcher dispatcher = request.getRequestDispatcher("register.jsp");
			dispatcher.forward(request, response);
		}else{
			User user = new User(0,username,password,name,address,phone,email,1,1);
			boolean result = dao.addUser(user);
			if(result)
				response.sendRedirect("registerSuccess.jsp");
			else{
				request.setAttribute("error", "注册失败");
				RequestDispatcher dispatcher = request.getRequestDispatcher("register.jsp");
				dispatcher.forward(request, response);
			}
		}
	}

}
